package com.letfox.ad.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import com.alibaba.fastjson.JSON;
import com.letfox.ad.model.ScreenContent;
import com.letfox.ad.service.ADServingMaterialService;
import com.letfox.ad.service.relation.ADColScreService;

public class QuartzTest {
	
	@Autowired
	private ADColScreService adColScreService;
	@Autowired
	private ADServingMaterialService adServingMaterialService;
	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	
    public static void main(String[] args) throws SchedulerException {
    	double percent=0.2;
    	int abroad=(int) (percent*20);
    	System.out.println(abroad);
//        //1.创建Scheduler的工厂
//        SchedulerFactory sf = new StdSchedulerFactory();
//        //2.从工厂中获取调度器实例
//        Scheduler scheduler = sf.getScheduler();
//
//
//        //3.创建JobDetail
//        JobDetail jb = JobBuilder.newJob(MyJob.class)
//                .withDescription("this is a ram job") //job的描述
//                .withIdentity("ramJob", "ramGroup") //job 的name和group
//                .build();
//
//        //任务运行的时间，SimpleSchedle类型触发器有效
//        long time=  System.currentTimeMillis() + 3*1000L; //3秒后启动任务
//        Date statTime = new Date(time);
//
//        //4.创建Trigger
//            //使用SimpleScheduleBuilder或者CronScheduleBuilder
//        Trigger t = TriggerBuilder.newTrigger()
//                    .withDescription("")
//                    .withIdentity("ramTrigger", "ramTriggerGroup")
//                    //.withSchedule(SimpleScheduleBuilder.simpleSchedule())
//                    .startAt(statTime)  //默认当前时间启动
//                    .withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")) //两秒执行一次
//                    .build();
//
//        //5.注册任务和定时器
//        scheduler.scheduleJob(jb, t);
//
//        //6.启动 调度器
//        scheduler.start();

    }
    
	public void writeRedisJob() throws Exception {
		List<Map<String, String>> list=adColScreService.queryPhysicIdAll();
		String key=null;
		String keyStarTime=null;
		String keyEndTime=null;
		Object startTime=null;
		Object endTime=null;
		double percent=0;
		int within=0;
		int abroad=0;
		String materJson=null;
		List<Map<String, String>> listWithinMaps=null;
		List<Map<String, String>> listAbroadMaps=null;
		Map<String, Object> materialMap=new HashMap<String, Object>();
		List<String> listWithinJson=new ArrayList<String>();
		List<String> listAbroadJson=new ArrayList<String>();
		for (Map<String, String> map : list) {
			key=map.get("SCREEN_ID");
			keyStarTime=key+","+"STARTTIME";
			keyEndTime=key+","+"ENDTIME";
			startTime=map.get("START_TIME");
			endTime= map.get("END_TIME");
			if (redisTemplate.hasKey(key) && redisTemplate.opsForList().size(key)>0) {
				redisTemplate.opsForValue().set(keyStarTime,startTime.toString() );
				redisTemplate.opsForValue().set(keyEndTime,endTime.toString());
			}else {
				percent=Double.parseDouble(map.get("PERCENT"));
				abroad=(int) (percent*20);
				within=20-abroad;		
				int x=0;
				//查询条件
				materialMap.put("screenId", key);
				materialMap.put("value", within);
				//查询广告主内播素材
				listWithinMaps=adServingMaterialService.queryWithinMaterial(materialMap);
				for (Map<String, String> map2 : listWithinMaps) {
					materJson=JSON.toJSONString(map2);
					listWithinJson.add(materJson);
				}
				//如果数量不足循环补充 
				if (listWithinJson.size()!=0) {
					for (int i = listWithinJson.size(); i < within; i++) {
						listWithinJson.add(listWithinJson.get(x));
						x++;
					}
				}
				if (abroad>0) {
					//设置时间格式
					SimpleDateFormat sDateFormat=new SimpleDateFormat("HH:mm:ss"); 
					//当前时间
				    String systemTime=sDateFormat.format(new Date());
					materialMap.put("value", abroad);
					materialMap.put("materialMap", systemTime);
					materialMap.put("endTime", systemTime);
					//查询广告主外播素材
					listAbroadMaps=adServingMaterialService.queryWithinMaterial(materialMap);
					for (Map<String, String> map2 : listAbroadMaps) {
						materJson=JSON.toJSONString(map2);
						listAbroadJson.add(materJson);
					}
					x=0;
					//如果数量不足循环补充 
					if (listAbroadJson.size()!=0) {
						for (int i = listAbroadJson.size(); i < abroad; i++) {
							listAbroadJson.add(listAbroadJson.get(x));
							x++;
						}
					}
				}
				listWithinJson.addAll(listAbroadJson);
				if (listWithinJson.size()!=0 && listWithinJson.size()<20) {
					x=0;
					for (int i = listWithinJson.size(); i < 20; i++) {
						listWithinJson.add(listWithinJson.get(x));
					}
				}
				if (listWithinJson.size()>0) {
					redisTemplate.delete(key);
					redisTemplate.delete(keyStarTime);
					redisTemplate.delete(keyEndTime);						
					redisTemplate.opsForValue().set(keyStarTime, startTime.toString());
					redisTemplate.opsForValue().set(keyEndTime, endTime.toString());
					//将素材存入redis
					redisTemplate.opsForList().rightPushAll(key, listWithinJson);
					//设置redis有效时间
					redisTemplate.expire(key, ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
					redisTemplate.expire(keyStarTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
					redisTemplate.expire(keyEndTime,  ScreenContent.REDISEXPIRE, TimeUnit.SECONDS);
				}
				listWithinJson.clear();
				listAbroadJson.clear();
			}
		}
	}
}
